<template>
  <div class="cus-image" :style="width + ';' + height">
    <el-image
      style="width: 100%; height: 100%"
      :src="src"
      :fit="fit"
      :alt="alt"
      :referrerPolicy="referrerPolicy"
      :zIndex="zIndex"
      :preview-src-list="previewSrcList"
      @click="cusPreviewImage"
    >
    </el-image>
    <span
      class="el-image-viewer__btn el-image-viewer__download"
      :class="{'display_none': showEdit}"
      v-show="dnFlag"
      @click="editImage"
    >
        <i class="el-icon-edit"></i>
    </span>
  </div>
</template>
<script>
export default {
  name: "cusImage",
  data() {
    return {
      dnFlag: false,
      wrapperElem: null,
      hidElClassNameLists: [
        "el-image-viewer__mask",
        "el-image-viewer__btn el-image-viewer__close",
        "el-icon-close",
      ],
    };
  },
  props: {
    src: {
      type: String,
      default: "",
    },
    showEdit: {
      type: Boolean,
      default: true,
    },
    previewSrcList: {
      type: Array,
      default: function () {
        return [];
      },
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    fit: {
      type: String,
      default: "",
    },
    alt: {
      type: String,
      default: "",
    },
    referrerPolicy: {
      type: String,
      default: "",
    },
    zIndex: {
      type: Number,
      default: 2000,
    },
  },
  methods: {
    cusPreviewImage() {
      this.$emit("previewImage", this.src);
      this.dnFlag = true;
      this.checkElemlents();
    },
    checkElemlents() {
      this.$nextTick(() => {
        let wrapper = document.getElementsByClassName(
          "el-image-viewer__wrapper"
        );
        if (wrapper.length > 0) {
          this.wrapperElem = wrapper[0];
          this.cusClickHandler();
        } else {
          this.checkElemlents();
        }
      });
    },
    cusClickHandler() {
      this.wrapperElem.addEventListener("click", this.hideCusBtn);
    },
    hideCusBtn(e) {
      let className = e.target.className;
      if (this.hidElClassNameLists.includes(className)) {
        this.dnFlag = false;
      }
    },
    editImage() {
      let imgUrl = document.getElementsByClassName(
        "el-image-viewer__canvas"
      )[0].children[0].src;
      this.$emit("editImage",imgUrl);
    },
  },
};
</script>
<style scoped lang="scss">
.cus-image {
  display: inline-block;
  .el-image-viewer__download {
    top: 40px;
    right: 100px;
    width: 40px;
    height: 40px;
    font-size: 24px;
    color: #fff;
    background: #606266;
    z-index: 3000; /* 如果该组件需要传递 z-index 的值，这个值也需要做成动态的 props */
    cursor: pointer;
    position: fixed;
  }
}
.display_none{
  display: none!important;
}
</style>
